<template>
	<view class="text-hide">
		<template v-for="(el, i) in textData" :key="i">
			<view v-if="el.isPhone" class="inline"  @click.stop="callPhone(el.text)">
				<text class="text-xn color-primary">{{ el.text }}</text>
			</view>
			<text v-else class="text-xn" :class="[textColorClass]">{{ el.text }}</text>
		</template>
	</view>
</template>

<script>
import { ref, watch } from 'vue';
const cellPhoneReg = /1[3456789]\d{9}/g;
export default {
	props: {
		value: String,
		textColorClass: {
			default: "color-main",
			type: String,
		}
	},
	setup(props) {
		const textData = ref([]);
		watch(
			() => props.value,
			(val) => {
				if (!val) {
					textData.value = [];
					return;
				}
				const phones = val.match(cellPhoneReg);
				if (phones && phones.length > 0) {
					const removeIndex = [];
					phones.forEach((phone, i) => {
						//判断每个电话前后是不是数字，其中一个是数字则不处理
						const index = val.indexOf(phone);
						const prefix = val.charAt(index - 1);
						const suffix = val.charAt(index + phone.length);
						// console.log(phone, prefix, suffix);
						if(!/\d/.test(prefix) && !/\d/.test(suffix)){
							//前后都不是数字
							val = val.replace(phone, "$");
						} else {
							removeIndex.push(i);
						}
					});
					for(let i=phones.length-1;i>=0;i--){
						if(removeIndex.includes(i)){
							phones.splice(i, 1);
						}
					}
					const arr = val.split('$');
					const _textData = [];
					arr.forEach((el, i) => {
						_textData.push({
							text: el,
						});
						if (phones[i]) {
							_textData.push({
								text: phones[i],
								isPhone: true,
							});
						}
					});
					textData.value = _textData;
				}else{
					textData.value = [{text: val}];
				}
			},
			{ immediate: true }
		);
		function callPhone(num) {
			num &&
				uni.makePhoneCall({
					phoneNumber: num,
				});
		}
		return {
			callPhone,
			textData,
		};
	},
};
</script>

<style></style>
